﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MisClient
{
    public partial class FrmConfirmMoney1 : BaseForm
    {
        private IBLL.ICustomer cusBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteCustomer();
        private IBLL.ICusDep cusDepBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteCusDep();
        private IBLL.ISacf sacfBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteSacf();

        public FrmConfirmMoney1()
        {
            InitializeComponent();
        }

        private void FrmConfirmMoney1_Load(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;
            this.openStarDate.Value = dt.Date.AddDays(-200);
            this.chkF.Text = "Y";
            this.txtOperUser.Text = accountUser.UserCode;
            this.txtDate.Text = DateTime.Now.ToShortDateString();
        }

        private void btnQuit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;
            this.openEndDate.Value = dt;
            this.openStarDate.Value = dt.Date.AddDays(-200);
            this.txtCusCode.Clear();
            this.txtCus.Clear();
            this.txtInvoiceNum.Clear();
            this.txtCusDepCode.Clear();
            this.txtCusDep.Clear();
            this.chkF.Clear();

            this.dataGridView1.Rows.Clear();
            this.dataGridView2.Rows.Clear();
            this.chkF.Text = "Y";

            this.openEndDate.Enabled = true;
            this.openStarDate.Enabled = true;
            this.txtCusCode.Enabled = true;
            this.txtInvoiceNum.Enabled = true;
            this.txtCusDepCode.Enabled = true;
            this.chkF.Enabled = true;

            this.txtNo.Clear();
            this.txtSm1.Clear();
            this.txtSm2.Clear();
            this.txtKd.Clear();
            this.txtTh.Clear();
            this.txtKp.Clear();
            this.txtSk.Clear();
            this.txtZw.Clear();
            this.txtBei.Clear();
            this.txtTotalNum.Clear();
            this.txtTotalQuantity.Clear();
            this.txtSumJe.Clear();
            this.txtNoSumJe.Clear();

            this.btnAdd.Enabled = false;
            this.btnPrint.Enabled = false;
            this.btnQuit.Enabled = false;
            this.btnCan.Enabled = true;

            this.openStarDate.Focus();
        }

        private void openStarDate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.openEndDate.Focus();
            }
        }

        private void openEndDate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtCusCode.Focus();
            }
        }

        private void txtCusCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!string.IsNullOrEmpty(this.txtCusCode.Text.Trim()))
                {
                    MisModel.Customer customer = cusBLL.GetById(this.txtCusCode.Text.Trim());
                    if (customer == null)
                    {
                        MessageBox.Show("无此代码或不属于本部分！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtCusCode.Focus();
                        return;
                    }
                    else
                    {
                        this.txtCus.Text = customer.Customer_;
                        MisModel.CusDep cusDep = cusDepBLL.GetById(this.txtCusCode.Text.Trim());
                        if (cusDep != null)
                        {
                            this.txtCusDepCode.Text = cusDep.CusDep_;
                            this.txtCusDep.Text = cusDep.Depart;
                        }
                    }
                }
                this.txtInvoiceNum.Focus();
            }
        }

        private void txtInvoiceNum_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (string.IsNullOrEmpty(this.txtInvoiceNum.Text.Trim()))
                {
                    MessageBox.Show("不能为空！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtInvoiceNum.Focus();
                    return;
                }
                else
                    this.txtCusDepCode.Focus();
            }
        }

        private void txtCusDepCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.chkF.Focus();
            }
        }

        private void chkF_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!string.IsNullOrEmpty(this.txtCusCode.Text.Trim()))
                {
                    MisModel.Customer customer = cusBLL.GetById(this.txtCusCode.Text.Trim());
                    if (customer == null)
                    {
                        MessageBox.Show("无此代码或不属于本部分！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtCusCode.Focus();
                        return;
                    }
                }
                if (string.IsNullOrEmpty(this.txtInvoiceNum.Text.Trim()))
                {
                    MessageBox.Show("不能为空！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtInvoiceNum.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(this.chkF.Text.Trim()))
                {
                    MessageBox.Show("不能为空！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.chkF.Focus();
                    return;
                }
                else if (!this.chkF.Text.Trim().ToUpper().Equals("Y") && !this.chkF.Text.Trim().ToUpper().Equals("N"))
                {
                    MessageBox.Show("应置为：Y(是)或N(否)！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.chkF.Focus();
                    return;
                }

                this.openEndDate.Enabled = false;
                this.openStarDate.Enabled = false;
                this.txtCusCode.Enabled = false;
                this.txtInvoiceNum.Enabled = false;
                this.txtCusDepCode.Enabled = false;
                this.chkF.Enabled = false;
                this.chkF.Enabled = false;

                this.txtNo.Enabled = true;
                this.txtNo.Focus();
                this.btnDelRecord.Enabled = true;
                this.btnAddRecord.Enabled = true;
                this.btnSave.Enabled = true;
            }
        }

        private void txtNo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Dictionary<string, object> dictionary = new Dictionary<string, object>();
                StringBuilder sb = new StringBuilder();
                sb.Append(" m.date>=@startDate and m.date<=@endDate");
                dictionary.Add("@startDate", this.openStarDate.Value.ToShortDateString());
                DateTime time = DateTime.Parse(this.openEndDate.Value.ToShortDateString());
                time=time.Date.AddDays(1);
                dictionary.Add("@endDate", time.ToShortDateString());
                sb.Append(" and m.cus_id=@cusId");
                dictionary.Add("@cusId", this.txtCusCode.Text.Trim());
                if (!string.IsNullOrEmpty(this.txtInvoiceNum.Text.Trim()))
                {
                    sb.Append(" and m.no_cus=@noCus");
                    dictionary.Add("@noCus", this.txtInvoiceNum.Text.Trim());
                }
                if (string.IsNullOrEmpty(this.txtNo.Text.Trim()))
                {
                    MessageBox.Show("请输入欲确认的单据编号！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtNo.Focus();
                    return;
                }
                sb.Append(" and m.no=@no");
                dictionary.Add("@no", this.txtNo.Text.Trim());
                DataTable dt = sacfBLL.GetArticleAll(sb.ToString(), dictionary);
                if (dt != null && dt.Rows.Count > 0)
                {
                    String cusId = dt.Rows[0]["CUS_ID"].ToString();
                    if (!cusId.Equals(this.txtCusCode.Text.Trim()))
                    {
                        MessageBox.Show(string.Format("此单据客户为{0}，不可操作！", cusId), "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtNo.Focus();
                        return;
                    }
                    String f2 = dt.Rows[0]["F2"].ToString();
                    String f3 = dt.Rows[0]["F3"].ToString();
                    String f4 = dt.Rows[0]["F4"].ToString();
                    if (!"1".Equals(f2) && !"1".Equals(f3) && !"".Equals(f4))
                    {
                        MessageBox.Show("单据应已提货且已开发票，不可操作！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtNo.Focus();
                        return;
                    }
                    if ("1".Equals(f4))
                    {
                        MessageBox.Show("单据已到款确认，不可操作！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtNo.Focus();
                        this.txtNo.Clear();
                        return;
                    }
                    string shopCode = dt.Rows[0]["SHOP_ID"].ToString();
                    this.txtSm1.Text = string.Format("{0}-{1}-{2}", dt.Rows[0]["CUS_ID"].ToString(), dt.Rows[0]["CUS_DEP"].ToString(), dt.Rows[0]["CUS_SHOP"].ToString());
                    decimal jeFs = 0;
                    decimal jeHs = 0;
                    int slP = 0;
                    short tax = 0;
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        jeFs += (decimal)dt.Rows[i]["JE_FS"];
                        jeHs += (decimal)dt.Rows[i]["JE_HS"];
                        slP += (int)dt.Rows[i]["SL_P"];
                        if (tax < (short)dt.Rows[i]["TAX"]) tax = (short)dt.Rows[i]["TAX"];
                    }
                    this.textBox16.Text = string.Format("{0}", tax);
                    this.txtSm2.Text = string.Format("库:{0} 未税额:{1} 含税额:{2} 件数:{3} 税率:{4}", shopCode, jeFs, jeHs, slP, tax);
                    this.txtKd.Text = string.Format("{0:f}", dt.Rows[0]["DATE"].ToString());
                    this.txtTh.Text = string.Format("{0:f}", dt.Rows[0]["D_TH"].ToString());
                    this.txtKp.Text = string.Format("{0:f}", dt.Rows[0]["D_KP"].ToString());
                    this.txtSk.Text = string.Format("{0:f}", dt.Rows[0]["D_JS"].ToString());
                    this.txtZw.Text = "Y";
                    this.txtTotalNum.Text = "0";
                    this.txtTotalQuantity.Text = "0";

                    this.txtBei.Enabled = true;
                    this.textBox15.Enabled = true;
                    this.textBox16.Enabled = true;
                    this.textBox17.Enabled = true;

                    this.txtBei.Focus();
                }
                else
                {
                    MessageBox.Show("查无符合条件的记录！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
        }

        private void btnAddRecord_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtNo.Text.Trim()))
            {
                MessageBox.Show("请输入合法的单据号！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtNo.Focus();
                return;
            }
            if (string.IsNullOrEmpty(this.txtSm1.Text.Trim()))
            {
                MessageBox.Show("请先确认单据号！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtNo.Focus();
                return;
            }
            IList<MisEntity.Sacf> sacfList = sacfBLL.FindAll(this.txtNo.Text.Trim());
            if (sacfList == null || sacfList.Count <= 0)
            {
                MessageBox.Show("无此单据号，请先设置！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtNo.Focus();
                return;
            }
            String no = this.txtNo.Text.Trim();
            int rowCount = this.dataGridView1.RowCount;
            if (rowCount >= 16)
            {
                MessageBox.Show("每单条数不可超过16条！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtNo.Focus();
                return;
            }
            if (rowCount > 0)
            {
                DataGridViewRow dr = null;
                for (int i = 0; i < rowCount; i++)
                {
                    dr = this.dataGridView1.Rows[i];
                    if (no.Equals(dr.Cells["invoice"].Value.ToString()))
                    {
                        MessageBox.Show("单据不可重复！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtNo.Focus();
                        return;
                    }
                }
            }
            decimal jeFs = 0;
            decimal jeHs = 0;
            foreach (MisEntity.Sacf L_Sacf in sacfList)
            {
                jeFs += (decimal)L_Sacf.JE_FS;
                jeHs += (decimal)L_Sacf.JE_HS;
            }
            String txtZw = this.txtZw.Text.Trim();
            if (!txtZw.ToUpper().Equals("Y"))
                txtZw = "N";
            String[] DataRow = new String[8];
            DataRow[0] = (rowCount + 1).ToString();
            DataRow[1] = no;
            DataRow[2] = txtZw;
            DataRow[3] = this.txtKd.Text.Trim();
            DataRow[4] = this.txtSm1.Text.Trim();
            DataRow[5] = this.txtSm2.Text.Trim();
            DataRow[6] = string.Format("{0}", jeHs);
            DataRow[7] = string.Format("{0}", jeFs);
            this.dataGridView1.Rows.Add(DataRow);

            decimal sumJe = jeHs;
            decimal noSumJe = jeFs;
            if (!string.IsNullOrEmpty(this.txtSumJe.Text.Trim()))
                sumJe += decimal.Parse(this.txtSumJe.Text.Trim());
            if (!string.IsNullOrEmpty(this.txtNoSumJe.Text.Trim()))
                noSumJe += decimal.Parse(this.txtNoSumJe.Text.Trim());
            this.txtSumJe.Text = string.Format("{0}", sumJe);
            this.txtNoSumJe.Text = string.Format("{0}", noSumJe);

            rowCount = this.dataGridView2.RowCount;
            String[] goodDataRow = new String[11];

            DataTable dt = sacfBLL.GetArticleGoodsAll(no);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                goodDataRow[0] = (rowCount + 1).ToString();
                goodDataRow[1] = dt.Rows[i]["no"].ToString();
                goodDataRow[2] = dt.Rows[i]["nono"].ToString();
                goodDataRow[3] = dt.Rows[i]["id"].ToString();
                goodDataRow[4] = dt.Rows[i]["goods"].ToString();
                goodDataRow[5] = dt.Rows[i]["unit"].ToString();
                goodDataRow[6] = dt.Rows[i]["sl"].ToString();
                goodDataRow[7] = dt.Rows[i]["price_fs"].ToString();
                goodDataRow[8] = dt.Rows[i]["je_fs"].ToString();
                goodDataRow[9] = dt.Rows[i]["tax"].ToString();
                goodDataRow[10] = dt.Rows[i]["NO_JS"].ToString();
                this.dataGridView2.Rows.Add(goodDataRow);
            }

            this.txtNo.Clear();
            this.txtSm1.Clear();
            this.txtSm2.Clear();
            this.txtKd.Clear();
            this.txtTh.Clear();
            this.txtKp.Clear();
            this.txtSk.Clear();

            this.txtNo.Focus();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string goods = "无金额调整";
            decimal cas = 0;
            string f7 = "0";
            decimal hj = decimal.Parse(this.txtSumJe.Text.Trim());
            decimal nhj = decimal.Parse(this.txtNoSumJe.Text.Trim());
            if (!string.IsNullOrEmpty(this.textBox17.Text.Trim()) && !"0".Equals(this.textBox17.Text.Trim()))
            {
                if (!"17".Equals(this.textBox16.Text.Trim()) && !"13".Equals(this.textBox16.Text.Trim()))
                {
                    MessageBox.Show("有金额调整,税率应为17或13！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.textBox16.Focus();
                    return;
                }
                hj += decimal.Parse(this.textBox17.Text.Trim());
                if (hj <= 0)
                {
                    MessageBox.Show(string.Format("有金额调整，整张发票合计金额为：{0}\n小于零，不可操作！", hj), "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.textBox16.Focus();
                    return;
                }
                if (MessageBox.Show(string.Format("有金额调整，整张发票合计金额为：{0}\n请检查各项目是否正确，是否保存[Y/N]？", hj), "提问窗", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    return;
                goods = string.Format("*{0}税{1} {2}", this.textBox17.Text.Trim(), this.textBox16.Text.Trim(), this.textBox15.Text.Trim());
                cas = decimal.Parse(this.textBox17.Text.Trim());
                f7 = "1";
                nhj += decimal.Parse(this.textBox17.Text.Trim()) * 100 / (100 + decimal.Parse(this.textBox16.Text.Trim()));
            }
            else
            {
                if (MessageBox.Show("无金额调整，\n请检查各项目是否正确，是否保存[Y/N]？", "提问窗", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    return;
            }
            if (hj<=0)
            {
                MessageBox.Show(string.Format("整张发票合计金额为：{0}\n小于零，不可操作！", hj), "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (this.dataGridView2.Rows.Count > 0)
            {
                IList<MisEntity.Sacf> list = new List<MisEntity.Sacf>();
                MisEntity.Sacf entity = null;
                DataGridViewRow dr = null;
                for (int i = 0; i < this.dataGridView2.Rows.Count; i++)
                {
                    dr = this.dataGridView2.Rows[i];
                    entity = new MisEntity.Sacf();
                    entity.NO = dr.Cells["data1"].Value.ToString();
                    entity.NONO = decimal.Parse(dr.Cells["data2"].Value.ToString());
                    entity.ID = dr.Cells["data3"].Value.ToString();
                    entity.OPER = accountUser.UserCode;
                    entity.F7 = char.Parse(f7);
                    entity.NO_JS = dr.Cells["noJs"].Value.ToString();
                    list.Add(entity);
                }
                sacfBLL.Article(list);
                this.btnSave.Enabled = false;
                this.btnCan.Enabled = false;
                MessageBox.Show(string.Format("单据已存盘，总金额：{0}。是否打印清单[y/n]？", hj), "提问窗", MessageBoxButtons.OK, MessageBoxIcon.Question);

                this.txtNo.Enabled = false;
                this.txtBei.Enabled = false;
                this.textBox15.Enabled = false;
                this.textBox16.Enabled = false;
                this.textBox17.Enabled = false;

                this.btnAdd.Enabled = true;
                this.btnAddRecord.Enabled = false;
                this.btnDelRecord.Enabled = false;
                this.btnPrint.Enabled = true;
                this.btnQuit.Enabled = true;
            } 
        }

        private void btnDelRecord_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.CurrentRow != null)
            {
                string no = this.dataGridView1.CurrentRow.Cells["invoice"].Value.ToString();
                this.dataGridView1.Rows.Remove(this.dataGridView1.CurrentRow);
                DataGridViewRow dr = null;
                for (int i = 0; i < this.dataGridView2.Rows.Count; i++)
                {
                    dr = this.dataGridView2.Rows[i];
                    if (no.Equals(dr.Cells["data1"].Value.ToString()))
                        this.dataGridView2.Rows.Remove(dr);

                }
            }
        }

        private void btnCan_Click(object sender, EventArgs e)
        {
            this.openStarDate.Enabled = false;
            this.openEndDate.Enabled = false;
            this.txtCusCode.Enabled = false;
            this.txtInvoiceNum.Enabled = false;
            this.txtCusDepCode.Enabled = false;
            this.chkF.Enabled = false;

            this.txtNo.Enabled = false;
            this.txtBei.Enabled = false;
            this.textBox15.Enabled = false;
            this.textBox16.Enabled = false;
            this.textBox17.Enabled = false;

            this.btnSave.Enabled = false;
            this.btnCan.Enabled = false;
            this.btnAdd.Enabled = true;
            this.btnAddRecord.Enabled = false;
            this.btnDelRecord.Enabled = false;
            this.btnPrint.Enabled = true;
            this.btnQuit.Enabled = true;
        }

        private void btnRef_Click(object sender, EventArgs e)
        {
            Point mousePoint = MousePosition;
            Point point = this.PointToClient(mousePoint);
            this.contextMenuStrip1.Show(this, point);
        }

        private void toolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("calc.exe");
        }

        private void txtBei_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (this.textBox33.Enabled)
                {
                    this.textBox33.Focus();
                }
                else
                {
                    this.textBox15.Focus();
                }
            }
        }

        private void textBox33_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.textBox15.Focus();
            }
        }

        private void textBox15_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.textBox16.Focus();
            }
        }

        private void textBox16_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.btnAddRecord.Focus();
            }
        }
    }
}
